package uscdb.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.log4j.Logger;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import uscdb.dao.ScriptDaoI;
import uscdb.dao.VersionDaoI;
import uscdb.model.Tscript;
import uscdb.model.Tversion;
import uscdb.pageModel.DataGrid;
import uscdb.pageModel.PageHelper;
import uscdb.pageModel.Script;
import uscdb.service.ScriptServiceI;
import uscdb.util.StringUtil.ClobUtil;
import uscdb.util.StringUtil.StringUtil;
import uscdb.util.poi.leoUtil;

@Service
public class ScriptServiceImpl implements ScriptServiceI {

	private static final Logger logger = Logger.getLogger(ScriptServiceImpl.class);

	@Autowired
	private ScriptDaoI scriptDao;

	@Autowired
	private VersionDaoI versionDao;

	@Override
	public DataGrid dataGrid(Script script, PageHelper ph) {
		DataGrid dg = new DataGrid();
		try {
			List<Script> scriptList = new ArrayList<>();
			List<Tscript> tscriptList = new ArrayList<>();
			Map<String, Object> params = new HashMap<>();
			String hql = "from Tscript t";
			tscriptList = scriptDao.find(hql + whereHql(script, params) + orderHql(ph), params, ph.getPage(),
					ph.getRows());
			for (Tscript tscript : tscriptList) {
				Script script2Page = new Script();
				BeanUtils.copyProperties(tscript, script2Page);
				script2Page.setVersionName(tscript.getTversion().getName());
				scriptList.add(script2Page);
			}
			dg.setTotal(scriptDao.count("select count(*) " + hql + whereHql(script, params), params));
			dg.setRows(scriptList);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		return dg;
	}

	/**
	 * 功能：拼装hql语句的过滤条件
	 * 
	 * @param script
	 *            对象
	 * @param params
	 *            过滤条件
	 * @return
	 */
	private String whereHql(Script script, Map<String, Object> params) {
		String hql = "";
		if (!StringUtil.isEmpty(script.getVersionName())) {
			hql += " where 1=1 ";
			if (!StringUtil.isEmpty(script.getVersionName())) {
				hql += " and t.tversion.name = :versionName";
				params.put("versionName", script.getVersionName().trim());
			}
			if (!StringUtil.isEmpty(script.getTestcaseNumber())) {
				hql += " and t.testcaseNumber like :testcaseNumber";
				params.put("testcaseNumber", "%%" + script.getTestcaseNumber().trim() + "%%");
			}
		}
		return hql;
	}

	/**
	 * 排序函数
	 * 
	 * @param ph
	 *            分页对象
	 * @return
	 */
	private String orderHql(PageHelper ph) {
		String orderString = "";
		if (ph.getSort() != null && ph.getOrder() != null) {
			orderString = " order by t." + ph.getSort() + " " + ph.getOrder();
		}
		return orderString;
	}

	@Override
	/**
	 * 功能：导入失败脚本excel
	 * 
	 * @param excelFile
	 *            excel对象
	 * @param script
	 *            对象
	 * @return 导入结果
	 */
	public String importScriptExcel(File excelFile, Script script) {
		String resultString = "无数据导入！";
		Boolean isImportFlag = false;
		String versionName = script.getVersionName();
		try {
			FileInputStream fileStream = new FileInputStream(excelFile);
			Workbook book = WorkbookFactory.create(fileStream);
			// 第2张表才是数据
			Sheet sheet = book.getSheetAt(1);
			for (int i = 1; i <= sheet.getLastRowNum(); i++) {
				Row ros = sheet.getRow(i);
				String testcaseResult = leoUtil.ConvertCellToStr(ros.getCell(5));
				// 如果用例结果是 Failed 才记录，其他结果暂时不处理
				if ("Failed".equals(testcaseResult.trim())) {
					// 获取testcase 的number，唯一的标识
					String testcaseNumber = leoUtil.ConvertCellToStr(ros.getCell(2));
					// 获取用例名称
					String name = leoUtil.ConvertCellToStr(ros.getCell(0));
					Tscript tscript = scriptDao.getByNumber(testcaseNumber);
					// 如果不为空，则失败数量+1
					if (null != tscript) {
						tscript.setTotalFailNum(tscript.getTotalFailNum() + 1);
						isImportFlag = true;
					} else {// 如果不存在，则new一个
						if (!StringUtil.isEmpty(versionName)) {
							Tversion tversion = versionDao.getByName(versionName);
							if (null != tversion) {
								Tscript tscriptNew = new Tscript(UUID.randomUUID().toString(), name, testcaseNumber, 1,
										tversion);
								isImportFlag = true;
								scriptDao.save(tscriptNew);
							} else {
								resultString = "系统没有该版本[" + versionName + "]，请创建！";
							}
						} else {
							resultString = "请输入版本号，才能导入！";
						}
					}
				}
			}
			if (isImportFlag) {
				resultString = "成功导入失败用例！";
			}

		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			resultString = "系统故障，请联系管理员";
		}
		return resultString;
	}

	@Override
	public Script get(String id) {
		Tscript t = scriptDao.get(Tscript.class, id);
		Script s = new Script();
		BeanUtils.copyProperties(t, s, new String[] { "note" });
		s.setVersionName(t.getTversion().getName());
		s.setNote(ClobUtil.getString(t.getNote()));
		return s;
	}

	@Override
	public void edit(Script script) {
		Tscript t = scriptDao.get(Tscript.class, script.getId());
		if (t != null) {
			BeanUtils.copyProperties(script, t, new String[] { "id", "note","name","testcaseNumber","totalFailNum","versionName" });
			t.setNote(ClobUtil.getClob(script.getNote()));
		}

	}

}
